<template> 
	<view>  
		<!-- 轮播图 -->
		<swiper class="screen-swiper" :indicator-dots="false" v-if="courseDetailsList.image!==0"
		 style="box-shadow:0px 4upx 20upx rgba(100,66,0,0.6);">
			<swiper-item class="radius">
				<image :src="!courseDetailsList.image?'/static/image/errorImg.svg':courseDetailsList.image" mode="aspectFill" :lazy-load="true" @error="imgError"></image>
			</swiper-item>
		</swiper>
  
		<!-- 老师信息 -->
		<teacher-info></teacher-info>
   
		<!-- 培训须知 -->
		<view class="padding bg-white margin-top-sm my-outline" style="line-height:1.8;color:#333;">
			<view class="flex"> 
				<view style="width:180upx;">适合年龄段:</view>
				<view v-if="courseDetailsList.scope">{{courseDetailsList.scope}}</view>
				<view v-else>未知年龄</view>
			</view>
			<view class="flex">
				<view style="width:180upx;">上课人数:</view>
				<view v-if="courseDetailsList.student_num">{{courseDetailsList.student_num}}</view>
				<view v-else>未知人数</view>
			</view> 
			<view class="flex">
				<view style="width:180upx;">每次课时长:</view>
				<view v-if="courseDetailsList.duration">{{courseDetailsList.duration}}分钟</view>
			</view> 
			<view class="flex" v-if="courseDetailsList.is_activity==1">
				<view style="width:180upx;">免费试学:</view>
				<view>试听课+音乐基础测评+到店送小礼物一份</view>
			</view>
		</view>
       
		<!-- 课程推荐 --> 
		<course :courses="courseDetailsList.recommend_course" :getPhoneNumber="getPhoneNumber"></course>
  
		<!-- 购买和预约 -->
		<view class="padding flex justify-around my-outline" style="background-color: #fff; position: fixed;left:0;bottom:0;width:100%;">
			
			<button class="cu-btn lg flex-twice" :class="courseDetailsList.is_activity==0?'single-btn':''" 
			style="font-size:36upx;background-color: #fff;border:2upx solid #000;" :open-type="getPhoneNumber" @getphonenumber="wxGetPhonenNumber" @tap="goBuy">立即购买</button>
			<!-- 购买模态框 -->
			<view class="cu-modal bottom-modal" :class="[buyModal?'show':'']">
				<view class="cu-dialog bg-white">
					<view class="cu-bar justify-end solid-bottom">
						<view class="content text-black">{{courseDetailsModal.course_name}}</view>
						<view class="action" @tap="hideBuyModal">
							<text class="cuIcon-close"></text>
						</view>
					</view>  
					<view class="solid-bottom">
						<!-- 老师信息 --> 
						<view class="padding flex justify-between align-center bg-white my-outline">
							<view class="flex align-center">
								<image class="cu-avatar lg round margin-right-sm" 
								:src="courseDetailsModal.teacher.avatar==null||courseDetailsModal.teacher.avatar==''?'/static/image/errorAvatar.svg':courseDetailsModal.teacher.avatar" mode="aspectFill" 
								:lazy-load="true" @error="avatarError">
								</image>
						 
								<view>
									<view class="flex align-center padding-bottom-xs">
										<view class="padding-right-sm text-lg text-black">{{courseDetailsModal.course_name}}</view>
										<my-tag :tag="courseDetailsModal.tag"></my-tag>
									</view> 
									<view class="text-left">
										<text class="padding-right-sm text-lg text-black">{{courseDetailsModal.teacher.teacher_name}}</text>
										<text class="text-lg" style="color:#999;">{{courseDetailsModal.teacher.level}}</text>
									</view>
								</view>
							</view>
							<view class="text-price text-red" style="font-size:40upx;" v-if="courseDetailsModal.unit_price*hour">{{courseDetailsModal.unit_price*hour}}</view>
						</view>
					</view>
					<view class="padding flex align-center bg-white solid-bottom" :class="studentsList.length==0?'justify-between':''">
						<view style="min-width: 112upx;">选择孩子</view>
						<view class="flex flex-wrap justify-end flex-sub" v-if="studentsList.length!==0">
							<view class="cu-tag radius text-df margin-left margin-bottom-xs" v-for="(item,index) in studentsList" :key="item.id"
							:class="childCur==index?'line-orange':''" @click="childSelect" :id="index">{{item.student_name}}</view>
						</view>
						<navigator class="text-orange" url="/pages/addChild/addChild" v-else>立即添加</navigator>
					</view>
					<view class="padding flex justify-between align-center solid-bottom">
						<view>课时数量</view>
						<!-- 计数器 -->
						<uni-number-box :value="hour" :min="1" @change="numChange"></uni-number-box>
					</view>
					<view class="padding">
						<form name='pushMsgFm' report-submit @submit='getFormId'>
							<button form-type="submit" class="cu-btn lg action bg-black" :loading="buyLoading" @tap="pay" style="font-size:36upx;width:100%;">立即购买</button>
						</form>
					</view>
				</view>
			</view>
			
			<button class="cu-btn lg flex-treble margin-left-sm bg-black" style="overflow: hidden;font-size:36upx;"
			v-if="courseDetailsList.is_activity==1" @tap="goApply" :open-type="getPhoneNumber" @getphonenumber="wxGetPhonenNumber">立即预约</button>
			 
		</view>
		
	<!-- 	<view class="cu-modal" :class="dateModal=='dateModal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">请选择</view>
					<view class="action" @tap="hideDateModal">
						<text class="cuIcon-close" style="color:#000;"></text>
					</view>
				</view>
				<view class="padding-xl">
					<ruiDatePicker fields="minute" start="2010-00-00 00:00" end="2030-12-30 23:59" :value="pickerValue" 
					@change="bindChange"></ruiDatePicker>
					
					<view class="flex align-center margin-top radius padding-right padding-left-lg" style="border: 2rpx solid #aaa;height:80upx;">
						<view class="title padding-right-lg">姓名：</view>
						<input class="text-left" placeholder="请输入你的姓名" name="input" v-modal="userName" @input="editUserName"></input>
					</view>
				</view>
				<view class="cu-bar bg-white justify-center align-center padding-lr-lg">
					<button class="cu-btn flex-sub" style="background-color: #fff;border:2upx solid #000;color:#000;" @tap="hideDateModal">取消</button>
					<button class="cu-btn margin-left flex-sub bg-black" :loading="loading" @tap="freeApply">确定</button>
				</view>
			</view>	
		</view> -->
		 
		<!-- 预约模态框 -->
		<view class="cu-modal bottom-modal" :class="[dateModal?'show':'']">
			<view class="cu-dialog bg-white">
				<view class="cu-bar justify-end solid-bottom">
					<view class="content text-black">{{courseDetailsModal.course_name}}</view>
					<view class="action" @tap="hideDateModal">
						<text class="cuIcon-close"></text>
					</view>
				</view> 
				<view class="solid-bottom">
					<!-- 老师信息 -->
					<view class="padding flex justify-between align-center bg-white my-outline">
						<view class="flex align-center">
							<image class="cu-avatar lg round margin-right-sm" 
							:src="courseDetailsModal.teacher.avatar==null||courseDetailsModal.teacher.avatar==''?'/static/image/errorAvatar.svg':courseDetailsModal.teacher.avatar" mode="aspectFill" 
							:lazy-load="true" @error="avatarError">
							</image>
					 
							<view>
								<view class="flex align-center padding-bottom-xs">
									<view class="padding-right-sm text-lg text-black">{{courseDetailsModal.course_name}}</view>
									<my-tag :tag="courseDetailsModal.tag"></my-tag>
								</view> 
								<view class="text-left">
									<text class="padding-right-sm text-lg text-black">{{courseDetailsModal.teacher.teacher_name}}</text>
									<text class="text-lg" style="color:#999;">{{courseDetailsModal.teacher.level}}</text>
								</view>
							</view>
						</view>
						<view class="text-price text-red" style="font-size:40upx;" v-if="courseDetailsModal.unit_price">{{courseDetailsModal.unit_price}}</view>
					</view>
				</view> 
				<view class="padding flex align-center bg-white solid-bottom" :class="studentsList.length==0?'justify-between':''">
					<view style="min-width: 112upx;">选择孩子</view>
					<view class="flex flex-wrap justify-end flex-sub" v-if="studentsList.length!==0">
						<view class="cu-tag radius text-df margin-left margin-bottom-xs" v-for="(item,index) in studentsList" :key="item.id"
						:class="childCur==index?'line-orange':''" @click="childSelect" :id="index">{{item.student_name}}</view>
					</view>
					<navigator class="text-orange" url="/pages/addChild/addChild" v-else>立即添加</navigator>
				</view>
				<view class="padding flex justify-between align-center solid-bottom">
					<view>请选择预约时间</view>
					<ruiDatePicker fields="minute" start="2010-00-00 00:00" end="2030-12-30 23:59" :value="pickerValue"
					@change="bindChange"></ruiDatePicker>
				</view>
				<view class="padding">
					<form name='pushMsgFm' report-submit @submit='getFormId'>
						<button form-type="submit" class="cu-btn lg action bg-black" :loading="applyLoading" @tap="freeApply" style="font-size:36upx;width:100%;">立即预约</button>
					</form>
				</view>
			</view>
		</view>
			
	</view>
</template>
 
<script>
	import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue'; //picker组件
	import teacherInfo from '@/components/teacherInfo.vue' //自定义老师信息组件
	import course from '@/components/course.vue' //自定义课程推荐
	import uniNumberBox from "@/components/uni-number-box/uni-number-box.vue" //数字输入框组件
	import myTag from '@/components/my-tag.vue'
	import {mapState} from 'vuex'

	export default {
		components: {
			ruiDatePicker,
			teacherInfo,
			course,
			uniNumberBox,
			myTag
		},
		data() {
			return {
				pickerValue: new Date().getFullYear() + ((new Date().getMonth() + 1) < 10 ? "-0" : "-") + (new Date().getMonth() + 1) + ((new Date().getDate() < 10 ? "-0" : "-") + new Date().getDate()) + ((new Date().getHours() < 10 ? " 0" : " ") + new Date().getHours()) + ((new Date().getMinutes() < 10 ? ":0" : ":") + new Date().getMinutes()),
				buyModal: false, //立即购买对话框
				dateModal: false,	//立即预约对话框
				courseId: '', //课程id
				otherCourseId: '',
				hour: 1, //计数器
				childCur: 0, //选中的孩子
				code: '',	//用户的随机code
				getPhoneNumber: '',
				userName: '',
				formId: '',
				applyLoading: false,
				buyLoading: false,
				courseDetailsModal: {},
				flag: false
			}
		},
		onLoad(obj) {
			let _this = this
			uni.showNavigationBarLoading()
			// 课程详情
			_this.getCourseDetail(obj.courseId)
			
			if(uni.getStorageSync('token')){
				// 基础信息
				this.getMe()
			}
			  
			// 保存课程id
			_this.courseId = obj.courseId
			
			// 获取用户随机code
			_this.getCode()
			
			uni.$on('applyEmit', function(data){
				// 保存课程id
				_this.otherCourseId = data.courseId
				
				// 课程详情
				_this.getCourseDetailModal('other')
				
				_this.showDateModal('other')
			})
			uni.$on('buyEmit', function(data){
				// 保存课程id
				_this.otherCourseId = data.courseId
				
				// 课程详情
				_this.getCourseDetailModal('other')
				
				_this.showBuyModal('other')
			})
		},
		onUnload() {
			uni.$off()
		},
		methods: {
			getCode(){
				let _this = this
				if(!_this.$store.state.meObj.phone){
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {
							_this.code = loginRes.code
							console.log('code', _this.code);
						}
					})
				}
			}, 
			// 获取用户手机号
			wxGetPhonenNumber(res) {
				if (res.detail.errMsg === 'getPhoneNumber:ok') {
					let encryptedData = res.detail.encryptedData
					let iv = res.detail.iv
					
					this.getPhone(encryptedData, iv)
				} 
			},
			// 获取用户手机号
			async getPhone(encryptedData, iv){
				
				let res = await this.$api.phone({code: this.code, encryptedData: encryptedData, iv: iv})
				if (res.statusCode === 200) {
					console.log('用户手机号', res.data.data)
					
					this.$store.dispatch('sendMe', res.data.data)
				}
			},
			// 课程详情
			async getCourseDetail(id) {
				let res = await this.$api.courseDetail(id)
				if (res.statusCode === 200) {
					uni.hideNavigationBarLoading()
					
					console.log('课程详情', res.data.data)
					
					this.$store.dispatch('sendCourseDetails', res.data.data)
				}
			},
			// 基础信息
			async getMe(){
				let res = await this.$api.me()
				if(res.statusCode === 200){
					uni.hideNavigationBarLoading()
					
					console.log('基础信息', res.data.data)
					
					this.$store.dispatch('sendMe', res.data.data)
				}
			},
			// 模态框的课程详情
			async getCourseDetailModal(info) {
				if(info === 'other'){
					let res = await this.$api.courseDetail(this.otherCourseId)
					if (res.statusCode === 200) {
						uni.hideNavigationBarLoading()
						
						console.log('课程详情', res.data.data)
						
						this.courseDetailsModal = res.data.data
						
						// this.$store.dispatch('sendCourseDetails', res.data.data)
					}
				}else{
					let res = await this.$api.courseDetail(this.courseId)
					if (res.statusCode === 200) {
						uni.hideNavigationBarLoading()
						
						console.log('课程详情', res.data.data)
						
						this.courseDetailsModal = res.data.data
						
						// this.$store.dispatch('sendCourseDetails', res.data.data)
					}
				}
				
			}, 
			// 打开对话框(用户已授权才显示)
			showBuyModal(info) {
				if(uni.getStorageSync('token')){
					if(info === 'other'){
						this.flag = true
					}
					if(this.$store.state.meObj.phone){
						// 我的学生列表
						this.getStudents('buyModal')
					}else{
						this.getPhoneNumber = 'getPhoneNumber'
					}
				}else{
					uni.navigateTo({
						url: '/pages/authorization/authorization'
					})
				}
			},
			// 关闭对话框
			hideBuyModal(e) {
				this.hour = 1
				
				this.buyModal = false
				this.flag = false
			},
			showDateModal(info){
				if(uni.getStorageSync('token')){
					if(info === 'other'){
						this.flag = true
					}
					if(this.$store.state.meObj.phone){
						// 我的学生列表
						this.getStudents('dateModal')
					}else{
						this.getPhoneNumber = 'getPhoneNumber'
					}
				}else{
					uni.navigateTo({
						url: '/pages/authorization/authorization'
					})
				}
			},
			hideDateModal(){
				this.dateModal = false
				this.flag = false
			},
			// 我的学生列表
			async getStudents(modalName){
				let res = await this.$api.students()
				if(res.statusCode === 200){
					if(modalName === 'buyModal'){
						this.buyModal = true
					}else{
						this.dateModal = true
					}
					console.log('我的学生列表', res.data.data)
					
					this.$store.dispatch('sendStudents', res.data.data)
				}
			},
			// 时间选择器点击【确定】按钮时触发的事件，参数为picker的当前的 value
			bindChange(value) {
				this.pickerValue = value
			},
			goApply(){
				// 课程详情
				this.getCourseDetailModal(this.courseId)
				this.showDateModal()
			},
			goBuy(){
				// 课程详情
				this.getCourseDetailModal(this.courseId)
				this.showBuyModal()
			},
			// 免费预约
			freeApply(){
				// 试课申请
				this.getCourseApply()
			}, 
			// 试课申请
			async getCourseApply() {
				if(this.$store.state.studentsList.length === 0){
					uni.showToast({
						title: '请先添加孩子',
						icon: 'none',
						mask: true
					})
				}else{
					this.applyLoading = true
					try{
						if(this.flag === true){
							let res = await this.$api.courseApply(this.otherCourseId, {
								apply_date: this.pickerValue, username: this.$store.state.studentsList[this.childCur].student_name, phone: this.$store.state.studentsList[this.childCur].phone, type: '1'
							})
							if (res.statusCode === 200 || res.statusCode === 201) {
								this.applyLoading = false
								
								console.log('试课申请', res)
								
								uni.showToast({
									title: '预约成功',
									mask: true,
									success: () => {
										setTimeout(() => {
											this.dateModal = false
											uni.redirectTo({
												url: '/pages/reservation/reservation'
											})
										}, 1500)
									} 
								})
							}
						}else{
							let res = await this.$api.courseApply(this.courseId, {
								apply_date: this.pickerValue, username: this.$store.state.studentsList[this.childCur].student_name, phone: this.$store.state.studentsList[this.childCur].phone, type: '1'
							})
							if (res.statusCode === 200 || res.statusCode === 201) {
								this.applyLoading = false
								
								console.log('试课申请', res)
								
								uni.showToast({
									title: '预约成功',
									mask: true,
									success: () => {
										setTimeout(() => {
											this.dateModal = false
											uni.redirectTo({
												url: '/pages/reservation/reservation'
											})
										}, 1500)
									} 
								})
							}
						}
						
					}catch(err){
						this.applyLoading = false
					}
				}
			},
			// 输入框值改变时触发的事件，参数为输入框当前的 value
			numChange(value) {
				this.hour = value
			},
			// 选择孩子
			childSelect(e) {
				this.childCur = e.currentTarget.id
			},
			// 立即购买
			pay() {
				if(this.$store.state.studentsList.length === 0){
					uni.showToast({
						title: '请先添加孩子',
						icon: 'none',
						mask: true
					})
				}else{
					// 创建订单
					this.found()
				}
			},
			// 获取formId
			getFormId(e){
				this.formId = e.detail.formId
			},
			// 创建订单
			async found() {
				this.buyLoading = true
				
				// 获取被选中的学生的id
				let id = this.$store.state.studentsList[this.childCur].id
				if(this.flag === true){
					let res = await this.$api.createOrder(this.otherCourseId, {
						student_id: id,
						class_hour: this.hour,
						form_id: this.formId
					})
					if (res.statusCode === 200) {
						console.log('创建订单', res)
						// 发起支付
						this.goPay(res.data.id)
					}
				}else{
					let res = await this.$api.createOrder(this.courseId, {
						student_id: id,
						class_hour: this.hour,
						form_id: this.formId
					})
					if (res.statusCode === 200) {
						console.log('创建订单', res)
						// 发起支付
						this.goPay(res.data.id)
					}
				}
				
			},
			// 发起支付
			async goPay(id) {
				uni.hideNavigationBarLoading()
				
				let res = await this.$api.pay(id)
				if(res.data.return_code === "FAIL"){
					this.buyLoading = false
					uni.showToast({
						title: '发起支付失败',
						icon: 'none',
						mask: true
					})
					return false
				}
				if(res.statusCode === 200){
					this.buyLoading = false
					
					console.log('发起支付', res);
					
					uni.requestPayment({
						timeStamp: res.data.timeStamp.toString(),
						nonceStr: res.data.nonceStr,
						package: res.data.package,
						signType: res.data.signType,
						paySign: res.data.paySign,
						success: res => {
							console.log('付款成功', res) 
							
							uni.showToast({
							    title: '付款成功',
								icon: 'success',
								success: () => {
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/index/index'
										})
									}, 1000)
								}
							});
						},
						fail: res => {
							console.log('付款失败', res)
							
							uni.showToast({
								title: '你取消了付款',
								icon: 'none',
								mask: true
							})
							
							this.buyModal = false
							this.hour = 1
						}
					})
				}
			},
			// 图片加载失败
			imgError: function (e) {
				this.$store.state.courseDetailsList.image = '/static/image/errorImg.svg'
			},
			// 头像加载失败
			avatarError: function () {
				this.courseDetailsModal.teacher.avatar = '/static/image/errorAvatar.svg'
			},
			editUserName(e){
				this.userName = e.detail.value
			},
		},
		computed: {
			...mapState(['courseDetailsList', 'studentsList', 'meObj'])
		}
	}
</script>

<style lang="scss">
	page{
		background-color: #f2f2f2 !important;
	}
	.single-btn{
		background-color: #000 !important;
		color: #fff !important;
	}
</style>
 